<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket Client</title>
</head>
<body>
    <h1>WebSocket Client</h1>
    <input type="text" id="messageInput" placeholder="Enter message">
    <button onclick="sendMessage()">Send</button>
    <div id="messages"></div>

    <script>
        // 手动指定服务端的端口号
        const ws = new WebSocket('ws://localhost:12345');

        ws.onopen = () => {
            console.log('Connected to server');
        };

        ws.onmessage = (event) => {
            const messagesDiv = document.getElementById('messages');
            if (messagesDiv) {
                const messageElement = document.createElement('div');
                messageElement.textContent = 'Received: ' + event.data;
                messagesDiv.appendChild(messageElement);
            } else {
                console.error('Element with id "messages" not found');
            }
        };

        function sendMessage() {
            const input = document.getElementById('messageInput');
            if (input) {
                const message = input.value.trim();
                if (message) {
                    try {
                        ws.send(message);
                        input.value = '';
                        console.log('Sent: ' + message);
                    } catch (error) {
                        console.error('Error sending message:', error);
                    }
                }
            } else {
                console.error('Element with id "messageInput" not found');
            }
        }

        ws.onerror = (error) => {
            console.error('WebSocket error:', error);
        };

        ws.onclose = () => {
            console.log('Disconnected from server');
            // 实现简单的重连机制
            setTimeout(() => {
                console.log('Attempting to reconnect...');
                reconnect();
            }, 5000); // 5秒后重试连接
        };

        function reconnect() {
            ws = new WebSocket('ws://localhost:12345');
            ws.onopen = () => console.log('Reconnected to server');
            ws.onmessage = (event) => {
                const messagesDiv = document.getElementById('messages');
                if (messagesDiv) {
                    const messageElement = document.createElement('div');
                    messageElement.textContent = 'Received: ' + event.data;
                    messagesDiv.appendChild(messageElement);
                }
            };
            ws.onerror = (error) => console.error('WebSocket error:', error);
            ws.onclose = () => console.log('Disconnected from server');
        }
    </script>
</body>
</html>
